﻿
using Exam.Model;
using ExaminationWeb.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ExaminationWeb
{
    public class UserAuthAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) )
            {
                return;
            }
            Exam.Model.UserInfo user = filterContext.HttpContext.Session[WebConstants.UserSession] as Exam.Model.UserInfo;
            if (user == null)//判断是否已经登录
            {
                string fromUrl = VerifyTool.Encode(filterContext.HttpContext.Request.Url.PathAndQuery, "Wicresoft");
                string redirectUrl = string.Format("?FromUrl={0}", fromUrl);
                string loginUrl = new UrlHelper(filterContext.RequestContext).Action("Login", "Account") + redirectUrl;
                filterContext.HttpContext.Response.Redirect(loginUrl.ToLower(), true);
            }
            //else
            //{
            //    string rawurll = filterContext.HttpContext.Request.RawUrl.ToLower();
            //    List<SysMenu> MenuList = filterContext.HttpContext.Session[WebConstants.UserRoleMenu] as List<SysMenu>;
            //    int rindex = rawurll.LastIndexOf("/");
            //    Guid guid;
            //    if (rindex > 0 && Guid.TryParse(rawurll.Substring(rindex + 1), out guid))
            //    {
            //        rawurll = rawurll.Substring(0, rindex);
            //    }
            //    if (MenuList.Where(e => e.MenuURL.ToLower().Contains(rawurll)).Count() == 0)
            //    {
            //        //    filterContext.HttpContext.Response.RedirectPermanent("/Account/NoPremission",true);
            //        //    filterContext.HttpContext.Response.Redirect("/Account/NoPremission", true);
            //        //   filterContext.HttpContext.Server.TransferRequest("/Login/Premission",false);
            //        //  filterContext.RequestContext.HttpContext.Response.Clear();
            //        //    filterContext.HttpContext.Server.TransferRequest("/Account/NoPremission", true);
            //        filterContext.HttpContext.Response.Redirect("/Account/NoPremission", true); //可以

            //        // filterContext.HttpContext.Server.Transfer("/Account/NoPremission", true); //不可以
            //        //  filterContext.HttpContext.Server.TransferRequest("/Account/NoPremission", true);
            //      //  filterContext.HttpContext.Server.Execute("/Account/NoPremission", true);
            //    }
            //}
        }
    }
}